# -*- coding: UTF-8 -*-
import paramiko
import re
import time


# 配置信息
SWITCH_IP = '10.2.245.134'
USERNAME = 'yunwei-admin'
PASSWORD = 'Sinotruk@2516'
ENABLE_PASSWORD = 'Sinotruk@2516'
PORT = 22

def send_command(shell, command, wait_time=2, prompt=r'[#>]\s*$', debug=True):
    """发送命令并等待提示符"""
    if debug:
        print(f"[发送命令] {command}")
    shell.send(command + '\n')
    time.sleep(wait_time)
    output = ''
    start_time = time.time()
    while True:
        if shell.recv_ready():
            part = shell.recv(4096).decode(errors='ignore')  # 忽略解码错误
            output += part
            if debug:
                print(f"[输出] {part}", end='')
        if re.search(prompt, output):
            break
        if time.time() - start_time > 20:
            raise TimeoutError(f"等待提示符 {prompt} 超时")
        time.sleep(0.5)
    return output

def parse_system_info(output):
    """解析系统基础信息（清理多余字符）"""
    info = {}
    # 使用正则提取并清理 \r 和空格
    info['desc'] = re.search(r'System Description:\s+(.+?)\s*[\r\n]+', output).group(1).strip() if re.search(r'System Description:', output) else 'N/A'
    info['name'] = re.search(r'System Name:\s+(.+?)\s*[\r\n]+', output).group(1).strip() if re.search(r'System Name:', output) else 'N/A'
    info['model'] = re.search(r'System Model ID:\s+(.+?)\s*[\r\n]+', output).group(1).strip() if re.search(r'System Model ID:', output) else 'N/A'
    info['uptime'] = re.search(r'System Up Time:\s+(.+?)\s*[\r\n]+', output).group(1).strip() if re.search(r'System Up Time:', output) else 'N/A'
    return info

def main():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(SWITCH_IP, port=PORT, username=USERNAME, password=PASSWORD)
        shell = ssh.invoke_shell()
        shell.settimeout(20)

        # 读取初始输出
        initial_output = send_command(shell, '', prompt='>', debug=False)

        # 进入特权模式
        enable_output = send_command(shell, 'enable', prompt='Password:|#', debug=False)
        if 'Password:' in enable_output:
            send_command(shell, ENABLE_PASSWORD, prompt='#', debug=False)
        else:
            print("直接进入特权模式")

        # 确认提示符为 #
        send_command(shell, '', prompt='#', debug=False)

        # 禁用分页
        send_command(shell, 'terminal length 0', debug=False)

        # 获取系统信息
        system_output = send_command(shell, 'show system', debug=False)
        system_info = parse_system_info(system_output)
        #print(json.dumps(system_info, indent=2))
        print("[XJ]系统-设备名#{}#正常#获取设备信息#无".format(system_info["name"]))
        print("[XJ]系统-设备描述#{}#正常#获取设备信息#无".format(system_info["desc"]))
        print("[XJ]系统-设备型号#{}#正常#获取设备信息#无".format(system_info["model"]))
        print("[XJ]系统-运行时间#{}#正常#获取设备信息#无".format(system_info["uptime"]))


    except Exception as e:
        print(f"错误详情: {str(e)}")
    finally:
        ssh.close()

if __name__ == '__main__':
    main()